package bupt.party.online.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import bupt.party.online.model.Admin;
import bupt.party.online.util.SessionConstants;
import bupt.party.online.video.Video;
import bupt.party.online.video.VideoMenu;
import bupt.party.online.video.VideoMgr;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ognl.OgnlValueStack;

/**
 * Video Action for BuptPartyOnlineLine website
 * 
 * @author lennydou
 * @version 1.0
 */
public class AdminVideoAction  extends Pagination implements ServletRequestAware,ServletResponseAware {
	HttpServletRequest request;
	HttpServletResponse response;
	
	private File video;
	private String videoFileName;
	private String videoContentType; // ContentType为固定格式
	
	private File videoPic;
	private String videoPicFileName;
	private String videoPicContentType;
	
	private String paginationCode;
	private String status;

	/**
	 * The default method
	 */
	public String execute() {
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		return SUCCESS;
	}

	public String view() {
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		
		return "view";
	}

	public String submitFile() {
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		String realPath = ServletActionContext.getServletContext().getRealPath("/videos");
		if (video != null) {
			File saveFile = new File(new File(realPath), videoFileName);
			if (!saveFile.getParentFile().exists()) {
				saveFile.getParentFile().mkdirs();
			}
			try {
				FileUtils.copyFile(video, saveFile);
			} catch (IOException e) {
				ActionContext.getContext().put("submitStatus", "抱歉, 上传失败");
				return "submitResult";
			}
			ActionContext.getContext().put("submitStatus", "恭喜, 上传成功");
		} else {
			ActionContext.getContext().put("submitStatus", "抱歉, 上传失败");
		}
		return "submitFile";
	}
	
	public String edit(){
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		HttpServletRequest request = ServletActionContext.getRequest();
		String actionType = request.getParameter("actionType");
		
		if(actionType != null && actionType.equals("modifyVideoInfo")){
			String videoId = request.getParameter("videoId");
			String videoCategoryId = request.getParameter("videoCategoryId");
			String videoName = request.getParameter("videoName");
			//videoName = videoName.length() > 25 ? videoName.substring(0, 25) + "......" : videoName;
			String videoIntroduction = request.getParameter("videoIntroduction");
			//videoIntroduction = videoIntroduction.length() > 270 ? videoIntroduction.substring(0, 270) + "......" : videoIntroduction;
			String videoStatus1 = request.getParameter("videoStatus1");
			
			// 上传图片
			String picName =null;
			if(videoPic != null){
				String realPath = ServletActionContext.getServletContext().getRealPath("/videos");
				picName = videoId.substring(7, videoId.length() - 4) +  videoPicFileName.substring(videoPicFileName.length() - 4);
				File saveFile = new File(new File(realPath), picName);
				if (!saveFile.getParentFile().exists()) {
					saveFile.getParentFile().mkdirs();
				}
				try {
					if(!saveFile.exists()){
						saveFile.createNewFile();
					}
					
					FileUtils.copyFile(videoPic, saveFile);
				} catch (IOException e) {
					e.printStackTrace();
					ActionContext.getContext().put("modifyStatus", "抱歉, 图片上传失败");
				} finally{
//					System.out.println("ee_savefile can read: " + saveFile.canRead());
//					System.out.println("ee_savefile can write: " + saveFile.canWrite());
				}
			}
			
			// 修改properies
			boolean flag = VideoMgr.getInstance().updateVideoInfo(videoId, videoCategoryId, videoName, picName, videoIntroduction, videoStatus1);
			if(flag == true){
				ActionContext.getContext().put("modifyStatus", "修改成功");
			}else {
				ActionContext.getContext().put("modifyStatus", "抱歉, 修改失败");
			}
		}else if(actionType != null && actionType.equals("displayVideoInfo")){
			String selectedVideos = request.getParameter("selectedVideoPaths");
			String[] selectedVideoArray = selectedVideos.split("#");
			
			if("swap".equals(selectedVideoArray[0]) && selectedVideoArray.length == 3){
				VideoMgr.getInstance().swapVideosUploadDate(selectedVideoArray[1], selectedVideoArray[2]);
			
			}else if("upup".equals(selectedVideoArray[0])){
				VideoMgr.getInstance().moveStep(selectedVideoArray[1], 1);
				
			}else if("down".equals(selectedVideoArray[0])){
				VideoMgr.getInstance().moveStep(selectedVideoArray[1], -1);
				
			}
		}
		
		String reloadFlag = request.getParameter("reload");
		if(reloadFlag != null && reloadFlag.length() > 0){
			try {
				VideoMgr.getInstance().updateVideos();
				VideoMenu.getInstance().loadMenu();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		// 这里开始获取数据
//		status = request.getParameter("status");
		List<Video> list = null;
		if(status == null || status.length() == 0){
			list = VideoMgr.getInstance().getAllVideos();
		} else {
			list = VideoMgr.getInstance().getVideosByStatus(status);
		}
		
		// Begin to Prepare page
		if(this.pageNow == null)
			pageNow = 1;
		totalResults = 0;
		paginationCode = "";
		totalResults =	list.size();
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
		if(totalResults > 0) {
			paginationCode = Pagination.getPaginationCode(pageSize, totalResults, pageNow);
		} else {
			paginationCode = "没有查询到有效数据！";
		}
//		pageNow = 1;
		
		int fromIndex = (pageNow - 1)*pageSize;
		int toIndex = fromIndex + pageSize;
		toIndex = toIndex > list.size() ? list.size() : toIndex;
		request.setAttribute("videoList", list.subList(fromIndex, toIndex));
		request.setAttribute("status", status);
		return "edit";
	}
	
	public String viewDemo(){
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		HttpServletRequest request = ServletActionContext.getRequest();
		String videoPic = request.getParameter("videopath");
		if(videoPic != null){
			Video item = VideoMgr.getInstance().getVideo(videoPic);
			request.setAttribute("video", item);
		}
		
		return "viewDemo";
	}
	
	public String publish(){
		HttpSession session = request.getSession();
		if(this.checkForAuth(SessionConstants.STU_LEVEL) ||(session.getAttribute(SessionConstants.SESSION_USER)==null) ) return "loginUI";//学生或者游客
		if(!this.checkForAuth(SessionConstants.ADMIN_THIRD_LEVEL)) return "noPermission";
		return "publish";
	}

	public File getVideo() {
		return video;
	}

	public void setVideo(File video) {
		this.video = video;
	}

	public String getVideoFileName() {
		return videoFileName;
	}

	public void setVideoFileName(String videoFileName) {
		this.videoFileName = videoFileName;
	}

	public String getVideoContentType() {
		return videoContentType;
	}

	public void setVideoContentType(String videoContentType) {
		this.videoContentType = videoContentType;
	}

	public File getVideoPic() {
		return videoPic;
	}

	public void setVideoPic(File videoPic) {
		this.videoPic = videoPic;
	}

	public String getVideoPicFileName() {
		return videoPicFileName;
	}

	public void setVideoPicFileName(String videoPicFileName) {
		this.videoPicFileName = videoPicFileName;
	}

	public String getVideoPicContentType() {
		return videoPicContentType;
	}

	public void setVideoPicContentType(String videoPicContentType) {
		this.videoPicContentType = videoPicContentType;
	}
	
	public String getPaginationCode() {
		return paginationCode;
	}
	public void setPaginationCode(String paginationCode) {
		this.paginationCode = paginationCode;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		
		this.response = arg0;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		
		this.request = arg0;
	}
	
	public void setStatus(String status){
		this.status = status;
	}
	
	public String getStatus(){
		return this.status;
	}
	
	public boolean checkForAuth(int requiredLevel){

		HttpSession session = request.getSession();
		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 
		
		if(!(user instanceof Admin)) return false;
		
		Admin admin	 = (Admin) user;
		
		return admin.getAdminLevel() == requiredLevel;
	}
	
	public void convertCategory(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String categoryId = (String)request.getParameter("categoryId");
		
		if(categoryId == null){
			return;
		}
		
		String categoryName = VideoMenu.getInstance().convertCategory(categoryId);
		// Write back
		OgnlValueStack stack = (OgnlValueStack) request.getAttribute("struts.valueStack");
		HttpServletResponse response = (HttpServletResponse) stack.getContext().get(StrutsStatics.HTTP_RESPONSE);
		try {
			response.setHeader("Content-Type", "text/plain; charset=UTF-8");
			response.getWriter().write(categoryName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String playVideo(){
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String videopath = request.getParameter("videopath");
		String categoryId = request.getParameter("categoryId");
	
		Video target = null;
		List<Video> videoList = VideoMgr.getInstance().getVideos(categoryId, Video.STATUS_PUBLISHED);
		for(int i = 0; i < videoList.size(); i++){
			Video temp = videoList.get(i);
			if(temp.getVideopath().trim().equals(videopath.trim())){
				target = temp;
			}
		}
		request.setAttribute("videoFullPath", target.getVideopath());
		request.setAttribute("videoName", target.getName());
		return "playVideo";
	}
}
